import 'dart:io';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
import 'package:flutter_ume/core/plugin_manager.dart';
import 'package:flutter_ume/flutter_ume.dart';
import 'package:flutter_ume_kit_console/flutter_ume_kit_console.dart';
import 'package:flutter_ume_kit_dio/flutter_ume_kit_dio.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/constant.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/modules/init/views/update_view.dart';
import 'package:mziot/app/tools/device.dart';
import 'package:mziot/app/tools/global_const.dart';
import 'package:mziot/app/tools/public_provider.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/locales.g.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'app/config/api.dart';
import 'app/routes/app_pages.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  String? initial;
  await GlobalConst.asyns();
  await Firebase.initializeApp();

  ThemeData themeData = ThemeData(
    appBarTheme: AppBarTheme(
      centerTitle: true,
      systemOverlayStyle: SystemUiOverlayStyle.dark,
      backgroundColor: Colors.white,
      shadowColor: Colors.transparent,
      iconTheme: IconThemeData(
        color: MColor.xFF000000,
      ),
      titleTextStyle: MFont.semi_Bold17.apply(color: MColor.xFF333333),
      toolbarHeight: 44,
    ),
    scaffoldBackgroundColor: Colors.white,
  );

  if (Platform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }

  GlobalConst.sharedPreferences?.setBool(Constant.kStart, true);
  try {
    initial = await AppPages.INITIAL(true);
    await Firebase.initializeApp();
    FirebaseAuth.instance;
  } finally {
    PluginManager.instance // 注册插件
      // ..register(WidgetInfoInspector())
      // ..register(WidgetDetailInspector())
      // ..register(ColorSucker())
      // ..register(AlignRuler())
      // ..register(ColorPicker()) // 新插件
      // ..register(TouchIndicator()) // 新插件
      // ..register(Performance())
      // ..register(ShowCode())
      // ..register(MemoryInfoPage())
      // ..register(CpuInfoPage())
      // ..register(DeviceInfoPanel())
      ..register(Console())
      ..register(DioInspector(dio: PublicProvider.instance!.onlyDio)); // 传入你的 Dio 实例
    // flutter_ume 0.3.0 版本之后
    // UMEWidget
    alertUpdate();
    final language = GlobalConst.sharedPreferences?.getInt(Constant.kLanguage) ?? 999;
    var local = Locale('en', 'US');
    if (language == 3) {
      local = Locale('de', 'DE');
    } else if (language == 2) {
      local = Locale('fr', 'FR');
    } else if (language == 1) {
      local = Locale('zh', 'CN');
    }
    await FlutterNativeTimezone.getLocalTimezone().then((value) {
      GlobalConst.sharedPreferences?.setString(Constant.timeZone, value);
    });

    runApp(
      RefreshConfiguration(
        enableLoadingWhenNoData: true,
        enableLoadingWhenFailed: true,
        hideFooterWhenNotFull: true,
        headerBuilder: () {
          return ClassicHeader(
            refreshStyle: RefreshStyle.Follow,
            textStyle: MFont.regular15.apply(color: Colors.white),
            refreshingIcon: loadingWidget,
            failedIcon: Icon(Icons.error, color: Colors.white),
            completeIcon: Icon(Icons.done, color: Colors.white),
            idleIcon: Icon(Icons.arrow_downward, color: Colors.white),
            releaseIcon: Icon(Icons.refresh, color: Colors.white),
          );
        },
        footerBuilder: () {
          return ClassicFooter(
            textStyle: MFont.regular15.apply(color: Colors.white),
            loadStyle: LoadStyle.ShowWhenLoading,
            failedIcon: Icon(Icons.error, color: Colors.white),
            loadingIcon: loadingWidget,
            canLoadingIcon: Icon(Icons.autorenew, color: Colors.white),
            idleIcon: Icon(Icons.arrow_upward, color: Colors.white),
          );
        },
        child: GetMaterialApp(
          debugShowCheckedModeBanner: false,
          translationsKeys: AppTranslation.translations,
          title: 'Mars Hydro',
          locale: local,
          fallbackLocale: Locale('en', 'US'),
          theme: themeData,
          initialRoute: initial,
          getPages: AppPages.routes,
          builder: EasyLoading.init(),
          // initialBinding: AllBinding(),
        ),
      ),
    );
    EasyLoading.instance
      ..displayDuration = const Duration(milliseconds: 2000)
      ..indicatorType = EasyLoadingIndicatorType.fadingCircle
      ..loadingStyle = EasyLoadingStyle.custom
      ..indicatorSize = 30.0
      ..radius = 10.0
      ..progressColor = Colors.yellow
      ..backgroundColor = MColor.skin.withAlpha(50)
      ..indicatorColor = Colors.white
      ..textColor = Colors.white
      ..maskColor = Colors.transparent
      ..maskType = EasyLoadingMaskType.black
      ..userInteractions = true
      ..dismissOnTap = false;

    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  }
}

void alertUpdate() {
  PublicProvider.request(path: Api.updateApp, params: {
    'appVersion': DeviceUtils.version ?? '1.0.0',
    'osVersion': Platform.isAndroid
        ? 'an'
            'droid'
        : 'ios'
  }).then((value) {
    if (value.isSuccess) {
      bool isNewest = value.data['isNewest'] ?? true;
      if (!isNewest) {
        Get.dialog(UpdateAppView(value.data));
      }
    }
  });
}
